//
//  ZBPaymentManager.m
//  dushuhu
//
//  Created by zhangbin on 8/30/14.
//  Copyright (c) qianfeng. All rights reserved.
//

#import "ZBPaymentManager.h"
#import "payRequsestHandler.h"
#import "WXApiObject.h"
#import "WXApi.h"
#import <UIKit/UIKit.h>
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
//AlixPaylibDelegate
@interface ZBPaymentManager ()

@end

@implementation ZBPaymentManager

+ (instancetype)shared {
	static ZBPaymentManager *_shared = nil;
	static dispatch_once_t onceToken;
	dispatch_once(&onceToken, ^{
		_shared = [[ZBPaymentManager alloc] init];
	});
	return _shared;
}

/**
 *  <#Description#>
 *
 *  @return <#return value description#>
 */
#pragma mark --   选择支付类型
- (void)pay:(ZBPaymentType)type
      price:(NSString *)price
    orderID:(NSString *)orderID
       name:(NSString *)name
description:(NSString *)description
callbackURLString:(NSString *)callbackURLString
  withBlock:(void (^)(BOOL success))block {
	if (type == ZBPaymentTypeAlipay) {
		[self alipayByOrderID:orderID price:price name:name description:description callbackURLString:callbackURLString];
		if (block) block (YES);
	} else if (type == ZBPaymentTypeWeixin) {
		[self weixinpayPrice:price orderID:orderID withBlock:^(BOOL success) {
			if (block) block(success);
		}];
    }else {
		if (block) block(YES);
	}
}

#pragma mark -- 动态生成订单号
- (NSString *)generateTradeNO
{
    static int kNumber = 15;
    NSString *sourceStr = @"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    NSMutableString *resultStr = [[NSMutableString alloc] init];
    srand(time(0));
    for (int i = 0; i < kNumber; i++)
    {
        unsigned index = rand() % [sourceStr length];
        NSString *oneStr = [sourceStr substringWithRange:NSMakeRange(index, 1)];
        [resultStr appendString:oneStr];
    }
    return resultStr;
}

#pragma mark -- 支付宝支付
-(void)alipayByOrderID:(NSString*)orderID
                 price:(NSString*)price
                  name:(NSString*)name
           description:(NSString*)description callbackURLString:(NSString*)callbackURLString{

    /*============================================================================*/
    /*=======================需要填写商户app申请的===================================*/
    /*============================================================================*/
    NSString *partner = @"2088901986198025";
    NSString *seller = @"ys@yaosha.com.cn";
    NSString *privateKey = @"MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAM9uPRvzfKsa5xBwEf2WpthZMX2QK9mngp9BWV2FEjM/o3s5HnKFgo/FLBVV3Rz0VZaNK5Vuyy+0tYThAv6ubgnXeAlcVn8GarKaWTJeR/xU0vl6B4O43cOst6k7n7xnmlsdY4jwtfJV/miVYTShc/ASFLMEZD5DXs98jgizDQ//AgMBAAECgYAqSe45cZV8CLsM1dxFF96iAuUdFTRrZkQyFY+TilqgihvZNlbnwCJTDz6ihuPSUFnWnKdDCthvvGa5VWpX49XY28lfMnvUlVoIudfrdLpXB6APSN82lwOW0c2Dk1vCV10Sll+Pdu+mYv7UDHD+HSRHrZAy8Zn7WNqGYuCdixdpKQJBAO6UmJIjo5mm2B6AZ5L7GvSgFcDx/30ymciyHwHl+7q/uDMfqgtsYrDRYZ6ZasZ8YNvZ2ZbD70BGsJ7tY0CQYoMCQQDek2iXjr+U3/Ddg21zwtXhWzRU2OdiCwtwBOaA8BPiw1amFxO/zsauI4Xbazb4aKWJWXBC8EjTlEsjKPadmTPVAkEApI6DqZDBX9KPkII6bkuabQ4Z0wpXkXAcWCxbbMDHXyirkT+O1vA8Jf9VWMIyvpK9cAaTqQSd+fSIECZmZfrwpwJBAIbjw1GGm6j4BxvYWO79N236Pj7lrWUH2IitD5044nRdehfyiG+IO3Sx5p/R3GCz2w7ge162DQzdJKRMYRmmDXkCQQDTOLHU8jHBACw++FLSX/Bde0iNnOMufZWnWAYVOKFA9KOkI/GPHq1F50+xZX4ZbA+ER/QdCh9MtDHVjSHYY/hN";

    /*============================================================================*/
    /*============================================================================*/
    /*============================================================================*/
    
    //partner和seller获取失败,提示
    if ([partner length] == 0 ||
        [seller length] == 0 ||
        [privateKey length] == 0)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示"
                                                        message:@"缺少partner或者seller或者私钥。"
                                                       delegate:self
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
        return;
    }
    
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    Order *order = [[Order alloc] init];
    order.partner = partner;
    order.seller = seller;
    order.tradeNO = [self generateTradeNO]; //订单ID（由商家自行制定）
    order.productName = name; //商品标题
    order.productDescription = description; //商品描述
    order.amount = price;//[NSString stringWithFormat:@"%.2f",price]; //商品价格
    order.notifyURL =  @"http://www.xxx.com"; //回调URL
    
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alisdkdemo";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(privateKey);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
        }];
        
         }
}



#pragma mark -- 微信支付入口
-(void)weixinpayPrice:(NSString*)price
              orderID:(NSString*)orderID
            withBlock:(void (^)(BOOL success))block{

    
    //{{{
    //本实例只是演示签名过程， 请将该过程在商户服务器上实现
    
    //创建支付签名对象
    payRequsestHandler *req = [payRequsestHandler alloc];
    //初始化支付签名对象
    [req init:APP_ID mch_id:MCH_ID];
    //设置密钥
    [req setKey:PARTNER_ID];
    
    //}}}
    
    //获取到实际调起微信支付的参数后，在app端调起支付
    NSMutableDictionary *dict = [req sendPay_demo];
    
    if(dict == nil){
        //错误提示
        NSString *debug = [req getDebugifo];
        
        [self alert:@"提示信息" msg:debug];
        
        NSLog(@"%@\n\n",debug);
    }else{
        NSLog(@"%@\n\n",[req getDebugifo]);
        //[self alert:@"确认" msg:@"下单成功，点击OK后调起支付！"];
        
        NSMutableString *stamp  = [dict objectForKey:@"timestamp"];
        
        //调起微信支付
        PayReq* req             = [[PayReq alloc] init];
        req.openID              = [dict objectForKey:@"appid"];
        req.partnerId           = [dict objectForKey:@"partnerid"];
        req.prepayId            = [dict objectForKey:@"prepayid"];
        req.nonceStr            = [dict objectForKey:@"noncestr"];
        req.timeStamp           = stamp.intValue;
        req.package             = [dict objectForKey:@"package"];
        req.sign                = [dict objectForKey:@"sign"];
        
        [WXApi sendReq:req];
    }
    
    

}

//客户端提示信息
- (void)alert:(NSString *)title msg:(NSString *)msg
{
    UIAlertView *alter = [[UIAlertView alloc] initWithTitle:title message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    
    [alter show];
 
}

# pragma mark -- 支付成功之后
- (void)afterPay:(ZBPaymentType)type withURL:(NSURL *)url {
	if (type == ZBPaymentTypeAlipay) {
//		[[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
//			
//		}];
	} else if (type == ZBPaymentTypeWeixin) {
//		[WXApi handleOpenURL:url delegate:self];
	}
}

@end
